<template>
  <div class="app-container">
    <div class="sku-add">
      <div class="sku-search">
        <el-form :inline="true" :model="queryParams" ref="searchForm">
          <el-form-item label="商品名称" prop="productName">
            <el-input v-model="queryParams.productName" placeholder="商品名称" />
          </el-form-item>
          <el-form-item label="商品ID" prop="id">
            <el-input v-model="queryParams.id" placeholder="商品ID" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchTable">筛选</el-button>
            <el-button @click="resetTable">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="sku-button">
        <el-button type="primary" @click="showAddForm">创建SKU</el-button>
      </div>
    </div>
    <el-table :data="tableData" v-loading="tableLoading">
      <el-table-column label="序号" type="index" :index="indexMethod" />
      <el-table-column prop="productNo" label="商品ID" />
      <el-table-column prop="productName" label="商品名称" />
      <el-table-column prop="price" label="价格" />
      <el-table-column prop="availableStock" label="在售库存" />
      <el-table-column prop="lockedStock" label="锁定库存" />
      <el-table-column prop="realTimeStock" label="实时库存" />
      <el-table-column prop="状态" label="状态">
        <template slot-scope="scope">
          <el-tag :type="scope.row.onlineFlag === 0 ? '' : 'success'">{{ scope.row.onlineFlag === 0 ? '未上线' : '已上线' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-switch style="margin-right:10px;" :value="scope.row.onlineFlag" :active-value="1" :inactive-value="0"
            @change="($event) => useSku($event, scope.row)">
          </el-switch>
          <el-button @click="editItemClick(scope.row)" type="text" size="small"
            v-if="scope.row.onlineFlag === 0">编辑</el-button>
          <el-button @click="materialItemClick(scope.row)" type="text" size="small">查看</el-button>
        </template>
      </el-table-column>
    </el-table>
    <InBody v-show="total > 0">
      <pagination :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getTableData" />
    </InBody>
    <el-dialog title="配置SKU" :visible.sync="dialogVisible" width="1000px" @closed="closeAddForm" destroy-on-close>
      <el-form :model="addForm" label-position="right" label-width="100px" ref="addForm" :rules="rules">
        <el-form-item label="商品名称" prop="productName">
          <el-input v-model="addForm.productName" placeholder="商品名称" :maxlength="15" />
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input-number v-model="addForm.price" controls-position="right" label="元" placeholder="价格" :min="0.01" />
        </el-form-item>
        <el-form-item label="净含量" prop="netWeight">
          <el-input-number v-model="addForm.netWeight" controls-position="right" label="g" placeholder="净含量" :min="1" />
        </el-form-item>
        <el-form-item label="卖点" prop="sellingPoints">
          <el-input v-model="addForm.sellingPoints" placeholder="卖点" :maxlength="15" />
        </el-form-item>
        <el-form-item label="商品描述" prop="description">
          <el-input type="textarea" :rows="4" v-model="addForm.description" placeholder="商品描述" :maxlength="200" />
        </el-form-item>
        <el-form-item label="图片" prop="productImage">
          <el-upload class="file-uploader" :action="`${baseUrl}/file/upload`" :show-file-list="false"
            accept=".png,.jpg,.jpeg" :on-success="handleFileSuccess">
            <img v-if="addForm.productImage" :src="addForm.productImage" class="file">
            <i v-else class="el-icon-plus file-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="核心功能" />
        <el-row v-for="(item, index) in addForm.coreFunctionList" :key="index + '0'">
          <el-col :span="8">
            <el-form-item label="图标" :prop="`coreFunctionList[${index}].image`" :rules="rules.listImage">
              <el-upload class="file-small-uploader" :action="`${baseUrl}/file/upload`" :show-file-list="false"
                accept=".png,.jpg,.jpeg"
                :on-success="(res) => { handleFormListSuccess(res, 'coreFunctionList', index) }">
                <img v-if="item.image" :src="item.image" class="file">
                <i v-else class="el-icon-plus file-small-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="文案" :prop="`coreFunctionList[${index}].text`" :rules="rules.listText">
              <el-input type="textarea" :rows="4" v-model="item.text" placeholder="文案" />
            </el-form-item>
          </el-col>
          <el-col :span="8" style="padding-left: 16px;" v-if="index > 0">
            <el-button icon="el-icon-minus" @click="removeCoreFunction(item, 'coreFunctionList')">删除</el-button>
          </el-col>
        </el-row>
        <el-form-item>
          <el-button icon="el-icon-plus" @click="addFormFunction('coreFunctionList')">新增一组信息</el-button>
        </el-form-item>
        <el-form-item label="原料来源" />
        <el-row v-for="(item, index) in addForm.materialSourceList" :key="index + '1'">
          <el-col :span="8">
            <el-form-item label="图标" :prop="`coreFunctionList[${index}].image`" :rules="rules.listImage">
              <el-upload class="file-small-uploader" :action="`${baseUrl}/file/upload`" :show-file-list="false"
                accept=".png,.jpg,.jpeg"
                :on-success="(res) => { handleFormListSuccess(res, 'materialSourceList', index) }">
                <img v-if="item.image" :src="item.image" class="file">
                <i v-else class="el-icon-plus file-small-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="文案" :prop="`coreFunctionList[${index}].text`" :rules="rules.listText">
              <el-input type="textarea" :rows="4" v-model="item.text" placeholder="文案" />
            </el-form-item>
          </el-col>
          <el-col :span="8" style="padding-left: 16px;" v-if="index > 0">
            <el-button icon="el-icon-minus" @click="removeCoreFunction(item, 'materialSourceList')">删除</el-button>
          </el-col>
        </el-row>
        <el-form-item>
          <el-button icon="el-icon-plus" @click="addFormFunction('materialSourceList')">新增一组信息</el-button>
        </el-form-item>
        <el-form-item label="营养成分表" required />
        <div class="tsFormItem">
          <div>表头</div>
          <el-form-item v-for="(item, index) in addForm.nutrients.headers" :key="index + '2'"
            :prop="`nutrients.headers[${index}]`" :rules="rules.listText">
            <el-input v-model="addForm.nutrients.headers[index]" :placeholder="`字段${index + 1}`" />
          </el-form-item>
        </div>
        <div class="tsFormItem" v-for="(item, index) in addForm.nutrients.raws" :key="index + '3'">
          <div>{{ `第${index + 1}行` }}</div>
          <el-form-item v-for="(chunk, number) in item" :key="number + '4'"
            :prop="`nutrients.raws[${index}][${number}]`" :rules="rules.listText">
            <el-input v-model="item[number]" :placeholder="`字段${number + 1}`" />
          </el-form-item>
          <div v-if="index > 0">
            <el-button icon="el-icon-minus" @click="removeCoreTsFunction(index, 'nutrients')">删除</el-button>
          </div>
        </div>
        <el-form-item>
          <el-button icon="el-icon-plus" @click="addFormTsFunction('nutrients')">新增一组信息</el-button>
        </el-form-item>
        <el-form-item label="文案" prop="nutrients.text" :rules="rules.listText">
          <el-input type="textarea" :rows="4" v-model="addForm.nutrients.text" placeholder="文案" />
        </el-form-item>
        <el-form-item label="公众号链接" prop="nutrients.href">
          <el-input v-model="addForm.nutrients.href" placeholder="公众号链接" />
        </el-form-item>
        <el-form-item label="核心实验数据" />
        <el-form-item label="标题" prop="experimentData.title">
          <el-input v-model="addForm.experimentData.title" placeholder="标题" />
        </el-form-item>
        <div class="tsFormItems">
          <div>表头</div>
          <el-form-item v-for="(item, index) in addForm.experimentData.headers"
            :prop="`experimentData.headers[${index}]`" :key="index + '4'">
            <el-input v-model="addForm.experimentData.headers[index]" :placeholder="`字段${index + 1}`" :maxlength="20" />
          </el-form-item>
        </div>
        <div class="tsFormItems" v-for="(item, index) in addForm.experimentData.raws" :key="index + '5'">
          <div>{{ `第${index + 1}行` }}</div>
          <el-form-item v-for="(chunk, number) in item" :key="number + '6'"
            :prop="`experimentData.raws[${index}][${number}]`">
            <el-input v-model="item[number]" :placeholder="`字段${number + 1}`" />
          </el-form-item>
          <div v-if="index > 0">
            <el-button icon="el-icon-minus" @click="removeCoreTsFunction(index, 'experimentData')">删除</el-button>
          </div>
        </div>
        <el-form-item>
          <el-button icon="el-icon-plus" @click="addFormTsFunction('experimentData')">新增一组信息</el-button>
        </el-form-item>
        <el-form-item label="文案" prop="experimentData.text">
          <el-input type="textarea" :rows="4" v-model="addForm.experimentData.text" placeholder="文案" />
        </el-form-item>
        <el-form-item label="实验详情" />
        <el-form-item label="产品有效性评定" prop="experimentDetail.effectiveness">
          <el-upload class="file-uploader" :action="`${baseUrl}/file/upload`" list-type="picture-card"
            accept=".png,.jpg,.jpeg" :on-success="handleFileListSuccess"
            :file-list="addForm.experimentDetail.effectiveness">
            <!-- <img v-if="addForm.experimentDetail.effectiveness" :src="addForm.productImage" class="file"> -->
            <i class="el-icon-plus file-uploader-icon"></i>
          </el-upload>
        </el-form-item>

        <el-row v-for="(item, index) in addForm.experimentDetail.animals" :key="index + '7'">
          <el-col :span="8">
            <el-form-item :label="`实验动物信息${index + 1}`" :prop="`item[${index}].image`">
              <el-upload class="file-small-uploader" :action="`${baseUrl}/file/upload`" :show-file-list="false"
                accept=".png,.jpg,.jpeg"
                :on-success="(res) => { handleFormListSuccess(res, 'experimentDetail', index) }">
                <img v-if="item.image" :src="item.image" class="file">
                <i v-else class="el-icon-plus file-small-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="名字" :prop="`item[${index}].text`">
              <el-input v-model="item.name" placeholder="名字" />
            </el-form-item>
          </el-col>
          <el-col :span="8" style="padding-left: 16px;" v-if="index > 0">
            <el-button icon="el-icon-minus" @click="removeCoreFunction(item, 'experimentDetail')">删除</el-button>
          </el-col>
        </el-row>
        <el-form-item>
          <el-button icon="el-icon-plus" @click="addFormFunction('experimentDetail')">新增一组信息</el-button>
        </el-form-item>
        <el-form-item label="储存&食用方式" />
        <el-row v-for="(item, index) in addForm.storageAndConsumptionMethod" :key="index + '8'">
          <el-col :span="8">
            <el-form-item label="图标" :prop="`storageAndConsumptionMethod[${index}].image`" :rules="rules.listImage">
              <el-upload class="file-small-uploader" :action="`${baseUrl}/file/upload`" :show-file-list="false"
                accept=".png,.jpg,.jpeg"
                :on-success="(res) => { handleFormListSuccess(res, 'storageAndConsumptionMethod', index) }">
                <img v-if="item.image" :src="item.image" class="file">
                <i v-else class="el-icon-plus file-small-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="文案" :prop="'storageAndConsumptionMethod.' + index + '.text'" :rules="rules.listText">
              <el-input type="textarea" :rows="4" v-model="item.text" placeholder="文案" />
            </el-form-item>
          </el-col>
          <el-col :span="8" style="padding-left: 16px;" v-if="index > 0">
            <el-button icon="el-icon-minus"
              @click="removeCoreFunction(item, 'storageAndConsumptionMethod')">删除</el-button>
          </el-col>
        </el-row>
        <el-form-item>
          <el-button icon="el-icon-plus" @click="addFormFunction('storageAndConsumptionMethod')">新增一组信息</el-button>
        </el-form-item>
        <el-form-item label="参考文献" prop="references">
          <el-input type="textarea" :rows="4" v-model="addForm.references" placeholder="参考文献" />
        </el-form-item>
        <el-form-item label="适用宠物类型" prop="applicablePetTypes">
          <el-select v-model="addForm.applicablePetTypes" placeholder="宠物类型">
            <el-option v-for="item in petType" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="适用年龄" prop="applicableAge">
          <el-select v-model="addForm.applicableAge" placeholder="适用年龄">
            <el-option v-for="item in ageType" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="保质期" prop="shelfLife">
          <el-input-number v-model="addForm.shelfLife" controls-position="right" label="月" placeholder="保质期" />
          月
        </el-form-item>
        <el-form-item label="库存" prop="availableStock">
          <el-input-number :disabled="editId !== undefined" v-model="addForm.availableStock" controls-position="right"
            placeholder="库存" />
        </el-form-item>
        <el-form-item label="功效" prop="efficacy">
          <el-input type="textarea" :rows="4" v-model="addForm.efficacy" placeholder="功效" />
        </el-form-item>
        <el-form-item label="成分" prop="ingredients">
          <el-input type="textarea" :rows="4" v-model="addForm.ingredients" placeholder="成分" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeAddForm">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="SKU详情" :visible.sync="detailVisible" width="1000px" @close="closeDetail">
      <el-descriptions :column="1" border :labelStyle="{ width: '150px' }">
        <el-descriptions-item label="商品名称">{{ detail.productName }}</el-descriptions-item>
        <el-descriptions-item label="价格">{{ detail.price }}元</el-descriptions-item>
        <el-descriptions-item label="重量">{{ detail.netWeight }}克</el-descriptions-item>
        <el-descriptions-item label="卖点">{{ detail.sellingPoints }}</el-descriptions-item>
        <el-descriptions-item label="商品图片">
          <el-image style="width: 100px; height: 100px" :src="detail.productImage"
            :preview-src-list="[detail.productImage]" />
        </el-descriptions-item>
        <el-descriptions-item label="商品描述">{{ detail.description }}</el-descriptions-item>
        <el-descriptions-item label="核心功能">
          <div class="smallList">
            <div class="smallItem" v-for="(item, index) in detail.coreFunctionList" :key="index">
              <span>
                <el-image style="width: 80px; height: 80px" :src="item.image" />
              </span>
              <span>{{ item.text }}</span>
            </div>
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="原料来源">
          <div class="bigList">
            <div class="bigItem" v-for="(item, index) in detail.coreFunctionList" :key="index">
              <span>
                <el-image style="width: 80px; height: 80px" :src="item.image" />
              </span>
              <span>{{ item.text }}</span>
            </div>
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="营养成分">
          <div class="ysTable">
            <div class="ysTableItem">
              <div>表头：</div>
              <div v-for="(item, idnex_) in detail.nutrients.headers" :key="idnex_">{{ item }}</div>
            </div>
            <div class="ysTableItem" v-for="(item, index) in detail.nutrients.raws">
              <div>第{{ index + 1 }}行：</div>
              <div v-for="(chunk, i) in item" :key="i">{{ chunk }}</div>
            </div>
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="核心实验数据">
          <div class="ysTable">
            <div class="ysTableItem ts">
              <div>表头：</div>
              <div v-for="(item, index_) in detail.experimentData.headers" :key="index_">{{ item }}</div>
            </div>
            <div class="ysTableItem ts" v-for="(item, index) in detail.experimentData.raws">
              <div>第{{ index + 1 }}行：</div>
              <div v-for="(chunk, _idnex) in item" :key="_idnex">{{ chunk }}</div>
            </div>
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="产品有效性评定">
          <el-image style="width: 100px; height: 100px" v-for="(item, index) in detail.experimentDetail.effectiveness"
            :key="index" :src="item" :preview-src-list="[item]" />
        </el-descriptions-item>
        <el-descriptions-item label="实验动物信息">
          <div class="smallList">
            <div class="smallItem" v-for="(item, index) in detail.experimentDetail.animals" :key="index">
              <span>
                <el-image style="width: 80px; height: 80px" :src="item.image" />
              </span>
              <span>{{ item.name }}</span>
            </div>
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="储存&使用方式">
          <div class="bigList">
            <div class="bigItem" v-for="(item, index) in detail.storageAndConsumptionMethod" :key="index">
              <span>
                <el-image style="width: 80px; height: 80px" :src="item.image" />
              </span>
              <span>{{ item.text }}</span>
            </div>
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="参考文献">{{ detail.references }}</el-descriptions-item>
        <el-descriptions-item label="适用宠物类型">{{ detail.applicablePetTypes }}</el-descriptions-item>
        <el-descriptions-item label="适用年龄">{{detail.applicableAge && ageType.find(item =>
          item.value === detail.applicableAge).label}}</el-descriptions-item>
        <el-descriptions-item label="保质期">{{ detail.shelfLife }}月</el-descriptions-item>
        <el-descriptions-item label="库存">
          {{ detail.availableStock }}
          <el-popover placement="bottom" trigger="click" v-model="showpopover">
            <div class="toolTipNumber">
              <el-input-number controls-position="right" v-model="addNumber" :min="1" @change="changeAddNumber" />
              <div class="toolTipNumberFooter">
                <el-button type="primary" @click="addSkuNumber">确定</el-button>
                <el-button @click="showpopover = false">取消</el-button>
              </div>
            </div>
            <el-button slot="reference">添加库存</el-button>
          </el-popover>
        </el-descriptions-item>
        <el-descriptions-item label="功效">{{ detail.efficacy }}</el-descriptions-item>
        <el-descriptions-item label="成分">{{ detail.ingredients }}</el-descriptions-item>
      </el-descriptions>
      <el-descriptions style="margin-top: 16px;" :column="1" border title="库存变更记录">
        <el-table :data="detail.stockList">
          <el-table-column prop="createTime" label="时间" />
          <el-table-column prop="createBy" label="操作人" />
          <el-table-column prop="changeTypeName" label="操作类型" />
          <el-table-column prop="changeAmount" label="数量" />
        </el-table>
      </el-descriptions>
      <el-descriptions style="margin-top: 16px;" :column="1" border title="编辑记录">
        <el-table :data="detail.editLogList">
          <el-table-column prop="editBy" label="编辑人" />
          <el-table-column prop="editTime" label="编辑时间" />
        </el-table>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script>
import { querySkuList, saveSku, skuUse, querySkuDetail, addSkuFloat } from '@/api/goods';
import { petType, ageType } from '@/constants/goods';
import { getBaseUrl } from "@/utils";

export default {
  mounted() {
    this.getTableData();
  },
  data() {
    return {
      petType,
      ageType,
      baseUrl: getBaseUrl(),
      tableData: [],
      tableLoading: false,
      dialogVisible: false,
      detailVisible: false,
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productName: '',
        id: ''
      },
      editId: undefined,
      initialForm: {
        productName: undefined,
        sellingPoints: undefined,
        price: undefined,
        netWeight: undefined,
        description: undefined,
        productImage: undefined,
        coreFunctionList: [{
          image: undefined,
          text: undefined
        }],
        materialSourceList: [{
          image: undefined,
          text: undefined
        }],
        nutrients: {
          headers: ['', '', ''],
          raws: [['', '', '']],
          text: undefined
        },
        nutrientsTextType: 'text',
        experimentData: {
          title: undefined,
          headers: ['', '', '', ''],
          raws: [['', '', '', '']],
          text: undefined
        },
        experimentDetail: {
          effectiveness: [],
          animals: [{
            image: undefined,
            name: undefined
          }]
        },
        storageAndConsumptionMethod: [{
          image: undefined,
          text: undefined
        }],
        references: undefined,
        applicablePetTypes: undefined,
        applicableAge: 0,
        shelfLife: undefined,
        availableStock: undefined,
        efficacy: undefined,
        ingredients: undefined
      },
      addForm: {
        productName: undefined,
        sellingPoints: undefined,
        price: undefined,
        netWeight: undefined,
        description: undefined,
        productImage: undefined,
        coreFunctionList: [{
          image: undefined,
          text: undefined
        }],
        materialSourceList: [{
          image: undefined,
          text: undefined
        }],
        nutrients: {
          headers: ['', '', ''],
          raws: [['', '', '']],
          text: undefined
        },
        experimentData: {
          title: undefined,
          headers: ['', '', '', ''],
          raws: [['', '', '', '']],
          text: undefined
        },
        experimentDetail: {
          effectiveness: [],
          animals: [{
            image: undefined,
            name: undefined
          }]
        },
        storageAndConsumptionMethod: [{
          image: undefined,
          text: undefined
        }],
        references: undefined,
        applicablePetTypes: undefined,
        applicableAge: 0,
        shelfLife: undefined,
        availableStock: undefined,
        efficacy: undefined,
        ingredients: undefined
      },
      rules: {
        productName: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        sellingPoints: [{ required: true, message: '请输入商品卖点', trigger: 'blur' }],
        price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
        netWeight: [{ required: true, message: '请输入商品净重', trigger: 'blur' }],
        description: [{ required: true, message: '请输入商品描述', trigger: 'blur' }],
        productImage: [{ required: true, message: '请上传商品图片', trigger: 'blur' }],
        listText: [{ required: true, message: '请输入该设置文案', trigger: 'blur' }],
        listImage: [{ required: true, message: '请上传该设置图片', trigger: 'blur' }],
        references: [{ required: true, message: '请输入参考文献', trigger: 'blur' }],
        applicablePetTypes: [{ required: true, message: '请选择适用宠物类型', trigger: 'blur' }],
        applicableAge: [{ required: true, message: '请选择适用宠物年龄', trigger: 'blur' }],
        shelfLife: [{ required: true, message: '请输入保质期', trigger: 'blur' }],
        availableStock: [{ required: true, message: '请设置库存', trigger: 'blur' }],
        efficacy: [{ required: true, message: '请输入产品功效', trigger: 'blur' }],
        ingredients: [{ required: true, message: '请输入产品成分', trigger: 'blur' }],
      },
      detail: {
        nutrients: {
          headers: [],
          raws: []
        },
        experimentData: {
          headers: [],
          raws: []
        },
        experimentDetail: {
          effectiveness: [],
          animals: []
        }
      },
      addNumber: 1,
      showpopover: false
    }
  },
  methods: {
    indexMethod(index) {
      return index + 1;
    },
    searchTable() {
      this.getTableData();
    },
    resetTable() {
      this.$refs.searchForm.resetFields();
      this.getTableData();
    },
    async getTableData() {
      this.tableLoading = true;
      const { code, rows, total } = await querySkuList({ ...this.queryParams })
      this.tableLoading = false
      if (code !== 200) return;
      this.tableData = rows
      this.total = +total
      this.$forceUpdate()
    },
    showAddForm() {
      this.dialogVisible = true
    },
    closeAddForm() {
      this.addForm = this.initialForm;
      this.dialogVisible = false;
      this.editId = undefined;
    },
    handleFileSuccess(res, file) {
      if (res.code === 200) {
        this.addForm.productImage = res.data.url
      }
    },
    handleFileListSuccess(res, file) {
      if (res.code === 200) {
        const urlObj = new URL(res.data.url);
        const fileName = urlObj.pathname.split('/').pop();
        this.addForm.experimentDetail.effectiveness.push({
          uid: Date.now().toString(36) + Math.random().toString(36).substring(2),
          name: fileName,
          url: res.data.url
        });
      }
    },
    handleFormListSuccess(res, obj, index) {
      if (res.code === 200) {
        if (obj !== 'experimentDetail') {
          this.addForm[obj][index]['image'] = res.data.url;
        } else {
          this.addForm[obj]['animals'][index]['image'] = res.data.url;
        }
      }
    },
    addFormFunction(obj) {
      if (obj !== 'experimentDetail') {
        this.addForm[obj].push({
          image: undefined,
          text: undefined
        })
      } else {
        this.addForm[obj]['animals'].push({
          image: undefined,
          name: undefined
        })
      }
    },
    addFormTsFunction(obj) {
      if (obj === 'nutrients') {
        this.addForm[obj]['raws'].push(['', '', ''])
      } else {
        this.addForm[obj]['raws'].push(['', '', '', ''])
      }

    },
    removeCoreFunction(item, obj) {
      if (obj !== 'experimentDetail') {
        const index = this.addForm[obj].indexOf(item)
        if (index !== -1) {
          this.addForm[obj].splice(index, 1)
        }
      } else {
        const index = this.addForm[obj]['animals'].indexOf(item);
        if (index !== -1) {
          this.addForm[obj]['animals'].splice(index, 1)
        }
      }
    },
    removeCoreTsFunction(index, obj) {
      this.addForm[obj]['raws'].splice(index, 1)
    },
    useSku(event, item) {
      skuUse({
        id: `${item.id}`,
        onlineFlag: event
      }).then(res => {
        if (res.code === 200) {
          this.$message({
            message: `商品已${event ? '上架' : '下架'}`,
            type: 'success'
          });
          this.getTableData();
        }
      })
    },
    closeDetail() {
      this.editId = undefined;
      console.log(233)
    },
    materialItemClick(item) {
      this.editId = item.id
      querySkuDetail({
        id: item.id
      }).then(res => {
        if (res.code === 200) {
          this.detailVisible = true;
          this.detail = res.data
        }
      })
    },
    editItemClick(item) {
      querySkuDetail({
        id: item.id
      }).then(res => {
        if (res.code === 200) {
          this.dialogVisible = true;
          this.editId = item.id;
          const formData = JSON.parse(JSON.stringify({ ...res.data }));
          const newList = [];
          formData.experimentDetail.effectiveness.map(item => {
            const urlObj = new URL(item);
            const fileName = urlObj.pathname.split('/').pop();
            newList.push({
              uid: Date.now().toString(36) + Math.random().toString(36).substring(2),
              name: fileName,
              url: item
            });
          })
          formData.experimentDetail.effectiveness = newList

          delete formData.realTimeStock;
          delete formData.productNo;
          delete formData.lockedStock;
          // delete formData.onlineFlag;
          console.log(formData)
          this.addForm = formData;
        }
      })
    },
    handleSubmit() {
      this.$refs.addForm.validate(async (valid) => {
        const params = JSON.parse(JSON.stringify({ ...this.addForm }));
        params.experimentDetail.effectiveness = params.experimentDetail.effectiveness.map(item => item.url);
        if (!valid) return;
        const { code } = await saveSku({ id: this.editId, ...params })
        if (code !== 200) return;
        this.$message({ message: `${this.editId ? '编辑' : '添加'}成功`, type: 'success' });
        this.closeAddForm();
        this.getTableData();
      })
    },
    changeAddNumber(value) {
      this.addNumber = value;
    },
    async addSkuNumber() {
      addSkuFloat({
        id: this.editId,
        stock: this.addNumber
      }).then(res => {
        if (res.code === 200) {
          this.$message({
            message: `添加成功`,
            type: 'success'
          });
          this.showpopover = false;
          querySkuDetail({
            id: this.editId
          }).then(res => {
            if (res.code === 200) {
              this.detail = res.data
            }
          })
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
.sku-add {
  width: 100%;
  height: auto;
  display: grid;
  grid-template-columns: 85% 15%;
  margin-bottom: 15px;

  div {
    &.sku-search {}

    &.sku-button {
      text-align: right;
    }
  }
}

.file-uploader {
  &::v-deep .el-upload {
    width: 150px;
    height: 150px;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;

    &:hover {
      border-color: #409EFF;
    }

  }

  .file-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 148px;
    height: 148px;
    line-height: 148px;
    text-align: center;
  }

  .file {
    width: 148px;
    height: 148px;
    display: block;
  }
}

.file-small-uploader {
  width: 80px;
  height: 80px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;

  &:hover {
    border-color: #409EFF;
  }

  .file-small-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 78px;
    height: 78px;
    line-height: 78px;
    text-align: center;
  }

  .file {
    width: 78px;
    height: 78px;
    display: block;
  }
}

.tsFormItem {
  display: grid;
  grid-template-columns: 100px auto auto auto 100px;

  div {
    &:first-child {
      text-align: right;
      padding-right: 10px;
      font-weight: bold;
      line-height: 36px;
    }
  }

  &::v-deep .el-form-item {
    .el-form-item__content {
      margin-left: 0 !important;
    }
  }
}

.tsFormItems {
  display: grid;
  grid-template-columns: 100px auto auto auto auto 100px;

  div {
    &:first-child {
      text-align: right;
      padding-right: 10px;
      font-weight: bold;
      line-height: 36px;
    }
  }

  &::v-deep .el-form-item {
    .el-form-item__content {
      margin-left: 0 !important;
    }
  }
}

.smallList {
  width: 100%;
  height: auto;

  .smallItem {
    width: 85px;
    height: auto;
    float: left;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;

  }
}

.bigList {
  width: 100%;
  height: auto;

  .bigItem {
    width: 100%;
    height: auto;
    display: grid;
    grid-template-columns: 80px auto;
    gap: 10px;

    span {
      display: inline-flex;
      align-items: center;
    }
  }
}

.ysTable {
  width: 100%;
  height: auto;

  .ysTableItem {
    width: 100%;
    display: grid;
    grid-template-columns: 60px auto auto auto;

    &.ts {
      grid-template-columns: 60px auto auto auto auto;
    }

    div {
      &:first-child {
        font-weight: bold;
        text-align: right;
      }

      text-align: center;
      line-height: 30px;
    }
  }
}

.toolTipNumber {
  // width: 250px;
  height: auto;

  .toolTipNumberFooter {
    margin-top: 16px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style>
